/**
 * Created by user on 2015/12/3.
 */

var async = require('async');
var mysqlUtil = require('../../../common/utils/mysqlUtil');
var Theme = mongoose.model('topic');
var Question = mongoose.model('question');
var replyIndex = mongoose.model('reply_index');
//var User = mongoose.model('user');
var Share = mongoose.model('mobile_app_share_content');
var Community = mongoose.model('community');
var toolUtil = require('../../../common/utils/toolUtil');

exports.themeListService = function(req ,callback) {
    var data = new Array();
    var body = req.body;
    logger.debug(body);
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    //var paged = (req.params.size && req.params.page);

    var option = body;
    //var sortType = paged ? {endDate:-1} : {};

    if (option.title) option.title = new RegExp(option.title);
    logger.debug(option);
    async.series([

        function (callbackInner) {
            Theme.count(option, function (err, count) {

                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },
        function (callbackInner) {

            Theme.find(option).sort({dateCreated:-1}).skip(index).limit(size)
                .exec(function (err, results) {

                    if (err) {
                        callbackInner(err);
                    } else {

                        results.forEach(function (theme) {
                            theme._doc.url = h5Host + 'app/topic/index.html'+ '?tid=' + theme._id;
                        });
                        data = results;
                        callbackInner(null, results);
                    }
                });

        },
        function (callbackInner) {

            async.each(data, function (theme, callbackInner2) {

                Question.find({topicId: theme._id}, function (err,result) {
                    if (theme && result != null) {
                        //话题发帖数
                        //logger.debug(result.length);
                        theme._doc['questionCount'] = result.length;
                    };

                    //话题发帖人数
                    Question.find({topicId: theme._id}).distinct('createdBy', function (err, result2) {
                        theme._doc['questionHeadCount'] = result2.length;
                        //回复数
                        var ids = new Array();
                        result.forEach(function (res) {
                            ids.push(res._id);
                        });
                        //logger.debug(ids);
                        replyIndex.count({contentId: {$in:ids}}, function (err, count) {
                            //logger.debug(count);
                            theme._doc['replyCount'] = count;
                            //回复人数
                            replyIndex.find({contentId: {$in:ids}}).distinct('repliedBy', function (err, result3) {
                                //logger.debug(result3.length);
                                theme._doc['replyHeadCount'] = result3.length;
                                callbackInner2();
                            });

                        });

                    });

                });

            }, function (err) {
                callbackInner(err, null);
            });

        }

        
    ], callback);

};

exports.themeAddService = function(req ,callback) {

    var body = req.body;

    var timestamp= new Date().getTime();
    var data = {
        title : body.title
        ,subTitle : body.subTitle
        ,desc : body.desc
        ,shareKey : timestamp
    };

    if (body.images) data.images = body.images;
    if (body.shareDesc) data.shareDesc = body.shareDesc;
    if (body.shareImage) data.shareImage = body.shareImage;


    logger.debug(data);
    var theme = new Theme(data);


    var share = new Share();
    share.key = timestamp;
    share.title = body.title;
    share.desc = body.shareDesc;
    share.image = body.shareImage;
    share.url =  h5Host + 'app/topic/share_topic.html'+ '?tid=' + theme._id;

    share.save(function(err, result) {
        theme.save(callback);
    });



    //temp.save(callback);

};

exports.themeEditService = function(req ,callback){

    var body = req.body.theme;
    //logger.debug(req);
    //logger.debug(body);

    var data = {
        title : body.title
        ,subTitle : body.subTitle
        ,desc : body.desc
    };
    if (body.images) data.images = body.images;
    if (body.shareImage) data.shareImage = body.shareImage;
    if (body.shareDesc) data.shareDesc = body.shareDesc;

    var data2 ={};
    if (body.title) data2.title = body.title;
    if (body.shareImage) data2.image = body.shareImage;
    if (body.shareDesc) data2.desc = body.shareDesc;

    logger.debug(data);
    logger.debug(data2);

    Share.update({key: body.shareKey}, data2, function(err) {
        Theme.update({_id:req.body.themeID}, data, callback);
    });


    //logger.debug(data);
    //Theme.update({_id: req.body.themeID}, data, callback);

};